#include "../cominc/algoFilterSmooth.h"
#include <stdlib.h>

static uint32_t algoFilterSmooth_GetAvg(algoFilterSmooth* pAlgo);
static void algoFilterSmooth_AddData(algoFilterSmooth* pAlgo, uint32_t newData);

void algoFilterSmoothInit(algoFilterSmooth* algo, uint32_t avgDepth)
{
    algo->Push = algoFilterSmooth_AddData;
    algo->Get = algoFilterSmooth_GetAvg;
    algo->len = avgDepth > ALGO_FILTER_SMOOTH_MAX ? ALGO_FILTER_SMOOTH_MAX : avgDepth;
    algo->itr = algo->buf;
    for (uint32_t idx = 0; idx < algo->len; idx++) {
        algo->buf[idx] = 0;
    }
}

static void algoFilterSmooth_AddData(algoFilterSmooth* pAlgo, uint32_t newData)
{
    if (pAlgo == NULL || pAlgo->itr == NULL || pAlgo->len == 0) {
        return;
    }
    *pAlgo->itr = newData;
    pAlgo->itr++; // 迭代器指向下一个元素
    if (pAlgo->itr == pAlgo->buf + pAlgo->len) {
        pAlgo->itr = pAlgo->buf;
    }
}

static uint32_t algoFilterSmooth_GetAvg(algoFilterSmooth* pAlgo)
{
    if (pAlgo == NULL || pAlgo->itr == NULL || pAlgo->len == 0) {
        return 0;
    }
    uint64_t result = 0;
    for (uint32_t idx = 0; idx < pAlgo->len; idx++) {
        result += pAlgo->buf[idx];
    }
    return result / pAlgo->len;
}
